import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/eventBus.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/model/userModel.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/page/user/detialUserPage.dart';
import 'package:gd_assistant/page/public/publicView.dart';

class userPage extends StatefulWidget {
   userPage({
    Key key,
    this.tatalKey,
    this.screenCb
  }): super(key: key);

  final tatalKey;
  Function screenCb;

  @override
  _userPageState createState() => _userPageState();
}

class _userPageState extends State<userPage> {
  bool isDark = false;

  var _scaffoldKey = new GlobalKey<ScaffoldState>();

  UserModel contentUserModel = new UserModel(items: []);
  int page = 0;
  String searchString = "";
  int status = -100;
  String doctorid = "";
  TextEditingController controller = TextEditingController(); 
  
  Widget _userListItem(BuildContext context, Items user) {
    return GestureDetector(
      onTap: (){
          Navigator.of(context).push(
            CustomRoute(detialUserPage(user: user))
          );
      },
      child: Container(
      height: 90,
      color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
      child: Container(
          child: Row(
            children: <Widget>[
              Container(
                padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Stack(
                    children: <Widget>[
                      ClipRRect(
                        borderRadius: BorderRadius.circular(34),
                        child: ExtendedImage.network(
                          GlobalConfig.qiNiuUri + ((user.avatar == null || user.avatar.isEmpty) ? "head.png" : user.avatar),
                          width: 68,
                          height: 68,
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        right: 0,
                        child: Offstage(
                          offstage: user.isMember == null || !user.isMember,
                          child: Image.asset("images/vip.png",width: 20,height: 20),
                        )
                      )
                    ],
                  ),
              ),
              Expanded(
                flex: 1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      user.name,
                      style: TextStyle(fontSize:18),
                      maxLines: 1,
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 10),
                    ),
                    Text(
                      user.phoneNum != null ? user.phoneNum : "",
                      style: TextStyle(fontSize:15, color: isDark ? Colours.dark_text : Colours.text_gray)
                    )
                  ],
                )
              ),
              Container(
                padding: EdgeInsets.fromLTRB(0, 18, 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Opacity(
                      opacity: user.appointTime == null || user.appointTime == 0 ? 0.0 : 1.0,
                      child: Text(
                          "下次预约：" + RelativeDateFormat.YMDformat(user.appointTime != null ? user.appointTime : 0),
                          style: TextStyle(fontSize:12, color: Colors.blue[400])
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 25),
                      child: Text(
                          RelativeDateFormat.format(DateTime.fromMillisecondsSinceEpoch(user.createdAt)) + " 注册",
                          style: TextStyle(fontSize:12, color: Colors.grey[600])
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );

  }

   RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  void _onRefresh() async{
    page = 0;
    TostUtil.showLoading(context, "搜索中...");
    UserModel result = await apiHandler.getAssistantSearchUserList(searchString,doctorid,status,0);
    TostUtil.removeLoading(context);
    setState(() {
      contentUserModel = result;
    });
    _refreshController.refreshCompleted();
  }

  void _onLoading() async{
    page ++;
    UserModel result = await apiHandler.getAssistantSearchUserList(searchString,doctorid,status,page);
    if(mounted)
    contentUserModel.items.addAll(result.items);
    setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    //监听医生选择事件
    EventBus().on("doctorChoose", (parmas){
      status = parmas["status"];
      doctorid = parmas["doctorId"];
      searchString = "";
      controller.text = "";
      _onRefresh();
    });
  }

  @override
  void dispose() {
    super.dispose();
    //widget关闭时 删除监听
    EventBus().off("doctorChoose");
    controller.dispose();
    _refreshController.dispose();
  }

  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text("用户管理",style:new TextStyle(color: Colors.white)),
        elevation: 0,
        automaticallyImplyLeading: false,
      ),
      body: Column(
        children: <Widget>[
          Container(
              height: 55,
              color: isDark ? Colours.dark_bg_color : Colours.bg_color,
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(left: 15),
                  ),
                  Expanded(
                    flex: 1,
                    child: TextFileWidget(
                      submit: (text) {
                        //每个筛选都是单独的
                        searchString = text;
                        status = -100;
                        doctorid = "";
                        EventBus().emit("searchChange",{});
                        _onRefresh();
                      },
                      controller: controller,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(10, 0, 15, 0),
                    child: FlatButton.icon(
                      icon: Icon(
                        Icons.border_color,
                        size: 12.0
                      ),
                      label: Text(
                        "筛选",
                        style: TextStyle(fontSize: 12, color: Colors.grey[500])
                      ),
                      color: isDark ? Colours.dark_bg_gray: Colours.bg_gray,
                      shape: RoundedRectangleBorder(
                        borderRadius: new BorderRadius.all(new Radius.circular(18.0))
                      ),
                      onPressed: () {
                        widget.screenCb();
                        widget.tatalKey.currentState.openEndDrawer();
                      },
                    )
                  ),
                ],
              )
            ),
          Expanded(
            flex: 1,
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              controller: _refreshController,
              header: ZLRefreshHeader(),
              footer: ZLRefreshFooter(),
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: getListContent()
            ),
          )
        ],
      )
    );
  }

  Widget getListContent() {
    if (contentUserModel.items.length == 0 && _refreshController.isLoading == false && _refreshController.isRefresh == false) {
      return  Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children:[
              Image.asset("images/doctorBg.png",width: 180),
              Padding(
                padding: EdgeInsets.only(top: 20),
                child: Text("暂无搜索用户"),
              )
            ]
          ),
      );
    }
    return ListView.separated(
            itemBuilder: (context, item) {
              if (item == 0) {
                return Offstage(
                  offstage: doctorid.length == 0,
                  child: Container(
                    padding: EdgeInsets.only(left: 20,right: 20),
                    height: 40,
                    color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                    child: Row(
                      children: <Widget>[
                        Icon(Icons.history, color: Colors.blue, size: 20),
                        Padding(
                          padding: EdgeInsets.only(left: 5),
                          child: Text("${contentUserModel.doctorName}医生", style:TextStyle(fontWeight: FontWeight.w600)),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 10),
                          child: Text("当前服务会员:${contentUserModel.currentMemberNum}"),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 10), 
                          child: Text("累计服务会员:${contentUserModel.totalMemberNum}"),
                        )
                      ],
                    ),
                  ),
                );
              }
              return _userListItem(context, contentUserModel.items[item-1]);
            },
            separatorBuilder: (BuildContext context, int index) {
              if (index == 0) {
                return Container();
              }
              return  new Divider(height: 1);
            },
            itemCount: contentUserModel.items.length + 1,
          );
  }
}



///搜索控件widget
class TextFileWidget extends StatelessWidget {
  TextFileWidget({
    Key key,
    this.submit,
    this.controller
  }): super(key: key);

  Function submit = (string){};
  TextEditingController controller;
  bool isDark = false;

  Widget buildTextField() {  
    //theme设置局部主题
    return TextField(
      cursorColor: Colors.white, //设置光标
      decoration: InputDecoration(
          icon: Icon(Icons.search, size:18),
          hintText: "请输入姓名或手机号",
          hintStyle: new TextStyle(fontSize: 14, color: isDark ? Colours.dark_text : Colours.text),
          border: InputBorder.none,
          contentPadding: EdgeInsets.fromLTRB(-10, -14, 0, 0)
          ),
      style: TextStyle(fontSize: 14, color: isDark ? Colours.dark_text : Colours.text),
      controller: controller,
      onSubmitted: (text) {
        submit(text);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    Widget editView() {
      return Container(
        decoration: new BoxDecoration(
          color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
          borderRadius: new BorderRadius.all(new Radius.circular(18.0)),
        ),
        height: 36,
        padding: EdgeInsets.fromLTRB(10, 0.0, 0.0, 0.0),
        child: Center(
          child: buildTextField(),
        ),
      );
    }
    return editView();

  }
}